import { Button, Checkbox, Form, message, Spin } from 'antd';
import React, { useCallback, useEffect, useMemo, useState } from 'react';

import DroppableList from '@/components/DroppableList';
import request from '@/utils/request';
import cls from 'classnames';
import { useParams } from 'umi';
import { PropertyEditor } from '../components/PropertyEditor';
import { PortalDefination, TemplateSolution } from '../declare';
import xxmModule from './components/xxm/index';

import style from './index.less';

function getTemplateSolution(tplId?: string, pageId?: string) {
    return request(`/api/template/editor?tplId=${tplId}&pageId=${pageId}`)
}

function saveTemplateSolution(data: Record<string, any>) {
    return request(`/api/template/save/view`, {
        method: 'POST',
        data
    })
}

/**
 * 发布当前页面
 * @param tplId 
 * @param pageId 
 */
function publishTemplate(tplId: string, pageId: string) {
    return request(`/api/template/publish/view?tplId=${tplId}&pageId=${pageId}`)
}

function getPortalModel(type: string) {
    const modelMap = {
        'banner': 'Ad',
        'noticeList': 'Notice',
        'shopListScroll': 'Goods',
        'shopListTwo': 'Goods',
        'shopListOne': 'Goods'
    }
    return modelMap[type]
}

function useEditor() {
    const [solution, setSolution] = useState<TemplateSolution>()
    const [currentPortal, setCurrentPortal] = useState<PortalDefination>()
    const [loading, setLoading] = useState<boolean>(false)
    const [saveLoading, setSaveLoading] = useState<boolean>(false)
    const [publishLoading, setPublishLoading] = useState<boolean>(false)


    const [homeData, setHomeData] = useState({});
    const [form] = Form.useForm()

    const [selectPortalIds, setSelectPortalIds] = useState<string[]>([]);
    const portals = solution?.portals || [];


    const selectList = useMemo<PortalDefination[]>(() => {
        return portals?.filter((it: any) => selectPortalIds.includes(it.id))
    }, [portals, selectPortalIds])


    const handleFormChange = useCallback(() => {
        const currentValue = form.getFieldsValue()
        setHomeData({
            ...homeData,
            ...currentValue
        })
    }, [form, homeData])


    const param = useParams<{
        pageId?: string
        tplId?: string
    }>()

    // 保存
    const handleSave = useCallback(() => {
        const data = solution?.portals.reduce<any[]>((p, next) => {
            const enabled = selectPortalIds.includes(next.id) ? 1 : 0
            const tg = homeData[next?.type]
            const cur = Array.isArray(tg) ? tg : { ...tg }
            if (cur?.strcutData) {
                cur.value = cur?.strcutData.map(tx => tx.id)
                delete cur?.strcutData
                cur.type = getPortalModel(next?.type)
            }
            p.push({
                templateId: parseInt(param.tplId, 10),
                pageId: parseInt(param.pageId, 10),
                portalId: next?.id,
                enabled,
                properties: JSON.stringify(cur),
                status: 'draft'
            })
            return p
        }, [])
        setSaveLoading(true)
        saveTemplateSolution({
            tpl: data
        }).then(rs => {
            message.success('保存成功!')
        })
            .finally(() => {
                setSaveLoading(false)
            })

    }, [homeData, selectPortalIds, solution, param])

    const handlePublish = useCallback(() => {
        setPublishLoading(true)
        publishTemplate(param.tplId, param.pageId)
            .then(rs => {
                message.success('发布成功')
            }).finally(() => {
                setPublishLoading(false)
            })
    }, [param])




    useEffect(() => {
        setLoading(true)
        getTemplateSolution(param.tplId, param.pageId).then(so => {
            const solution = so.data?.solution as TemplateSolution
            solution.portals.filter(tx => {
                // @ts-ignore
                tx.properties = JSON.parse(tx.properties as string)
            })
            setSolution(solution)

            form.setFieldsValue(solution.data)
            setHomeData(solution.data)
            setSelectPortalIds(solution.selectIds)

            // if (solution.data && Object.keys(solution.data).length) {
            //     //@ts-ignore
            //     setSelectPortalIds(Object.values(solution.data).filter(tx => tx.enabeld).map(tx => tx.id))
            // }
            // setCurrentPortal(solution.portals[0])
        }).finally(() => {
            setLoading(false)
        })

        // getHome().then(res => {
        //     if (res?.code === 0) {
        //         setHomeData(res?.data);
        //     }
        // });


    }, [form])

    return {
        loading,
        solution,
        homeData,
        currentPortal,
        setCurrentPortal,
        form,
        selectPortalIds,
        setSelectPortalIds,
        selectList,
        handleFormChange,
        handleSave,
        saveLoading,
        handlePublish,
        publishLoading
    }

}


const Furnish: React.FC<{}> = () => {
    const { solution, loading, currentPortal, homeData,
        setCurrentPortal, form,
        setSelectPortalIds, selectPortalIds,
        selectList,
        handleFormChange,
        handleSave,
        saveLoading,
        handlePublish,
        publishLoading
    } = useEditor()


    return (
        // <PageHeaderWrapper>
        <div>
            <div className={style['furnish_top']}>
                <div className={style['furnish_back']}></div>
                <div className={style['furnish_name']}>{solution?.page?.title}</div>
                <div className={style['furnish_opt']}>
                    <Button type='primary' ghost loading={saveLoading} onClick={handleSave}>保存</Button>
                    <Button type="primary" onClick={handlePublish} loading={publishLoading}>发布</Button>
                </div>
            </div>
            <Spin spinning={loading}>
                <div className={style['furnish_wrap']}>
                    <div className={style['furnish_left']}>
                        <div className={style['furnish_left_title']}>页面管理</div>
                        <ul className={style['furnish_left_ul']}>
                            <Checkbox.Group value={selectPortalIds} onChange={(v) => {
                                setSelectPortalIds(v);
                            }} >
                                {
                                    solution?.portals?.map((tx, index) => (
                                        <Checkbox key={index} value={tx.id}>{tx.title}</Checkbox>
                                    ))
                                }
                            </Checkbox.Group>
                        </ul>
                    </div>
                    <div className={style['furnish_content']}>
                        <DroppableList
                            value={selectList}
                            grid={0}
                            // onChange={(val) => handleSort(val)}
                            orderKey='sort_id'>
                            {(it: any, index: number) => {
                                const Com = xxmModule[it.type];
                                return (
                                    <div key={index} className={cls({
                                        [style['module_wrapper']]: true,
                                        [style['module_selected']]: it.id === currentPortal?.id

                                    })} onClick={() => setCurrentPortal(it)}><Com homeData={homeData} /></div>
                                );
                            }}
                        </DroppableList>
                        {/* {
                        selectList.map(it => {
                            const Com = xxmModule[it.type];
                            return <div className={style['module_wrapper']}><Com homeData={homeData} /></div>
                        })
                    } */}
                        {/* <img src={xxmImg} className={style['furn_img']} /> */}
                    </div>
                    <div className={style['furnish_right']}>
                        <div className={style['furnish_left_title']}>属性</div>
                        {currentPortal && <PropertyEditor
                            defination={currentPortal}
                            values={{}}
                            form={form}
                            formChange={handleFormChange}
                        />
                        }
                    </div>
                </div>
            </Spin>
        </div>
    );
};

export default Furnish;
